import store from "@/store";

window.flapRoutes = null

const state = {
    routes: [],//存放原始路由信息
    pages:null, // 存放每个模块的路由
}

const mutations = {
    SET_ROUTES: (state, routes) => {
        state.routes = routes
    }, // 存放当前有得路由表信息
    SET_PAGES: (state, pages) => {
        state.pages = pages
    }, // 存放当前有得路由表信息
    SET_OPERATE:(state, operates) =>{
        state.operates = operates
    } // 存放当前项目按钮与tab的权限字段
}

const actions = {
    generateRoutes({ commit }, auth) {
        return new Promise((resolve) => {
            const operates= {} // 暂存所有按钮或者tab的key，用于权限
            const pages = {} // 用于存放所有菜单下的路由
            function trsfRouter(arr,flag,key){
                for (let i = 0; i < arr.length; i++) {
                    const arrElement = arr[i]
                    if(flag){ // 第一次
                        operates[arrElement.moduleKey] = []
                        pages[arrElement.moduleKey] = []
                    }
                    if(arrElement.moduleType!=='Page'){
                        if(!flag&&key){
                            operates[key].push(arrElement.moduleKey)
                        }
                    }else{
                        if(location.pathname===arrElement.moduleUrl){
                            store.dispatch('tabs/setRouter',arrElement)
                        }
                        if(!flag&&key){
                            pages[key].push(arrElement)
                        }
                    }
                    trsfRouter(arrElement.children,false,key||arrElement.moduleKey)
                }
            }
            trsfRouter(auth,true)
            commit('SET_ROUTES', auth)
            commit('SET_PAGES', pages)
            commit('SET_OPERATE', operates) // 按钮分组
            window.flapRoutes = auth
            resolve()
        })
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}
